package com.ynunicom.dc.dingdingcontractapp.configuration.schedule.cleanschedule;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Conditional;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author: jinye.Bai
 * @date: 2020/6/8 16:37
 */
@Component
@Conditional(CleanScheduleCondition.class)
@Slf4j
public class CleanSchedule {

    @Getter
    @Setter
    @Value("${contract.filePath}")
    private String filePath;

    /**
     * 定时清理任务，7天一次，清理目标为最后一次修改时间距今大于一年的
     */
    @Scheduled(fixedDelay = 604800000,initialDelay = 2000)
    public void cleaner(){
        File file = new File(filePath);
        File[] files = file.listFiles();
        if (Objects.requireNonNull(files).length<1){
            log.info("定期清理：没有文件需要清理");
            return;
        }
        List<File> fileList = Arrays.asList(Objects.requireNonNull(files));
        for (File innerFile :
                fileList) {
            long timeLength = System.currentTimeMillis() - innerFile.lastModified();
            long aYearLength = 31536000000L;
            if (timeLength>=aYearLength){
                if (innerFile.delete()){
                    log.info("定期清理：执行定期清理成功[{}]",innerFile.getName());
                }
            }
        }
    }
}
